 package com.framework.base.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import net.sourceforge.jeval.EvaluationException;
import net.sourceforge.jeval.Evaluator;

/**
 * @Copyright @ 2013
 * All right reserved
 * @version 创建时间：Created on 2013-4-16
 * @author 作者：Create by www.360buyli.com
 * @Email: 360buyli@gmail.com
 * @description 此类用于处理根据数据公式进行运算
 */

public class DOperator {
	private static Properties expProperties;
	
	/**
	 * 用于读取属性文件中的公式
	 * 
	 * @param key
	 * @returnv
	 */
	private static String getConfValue(String key) {
		if (expProperties == null) {
			DOperator.expProperties = new Properties();
			try {
				DOperator.expProperties.load(DOperator.class
						.getResourceAsStream("/expression.properties"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Object obj = expProperties.get(key);
		if (obj == null) {
			return "";
		} else {
			return obj.toString();
		}
	}
	/**
	 * 根据表达式和传入的值 自动计算结果
	 * @param expKey 指定表达式
	 * @param paramMap 将值封装到map中传入
	 * @return
	 * @throws EvaluationException
	 */
	public static String doEvaluate(String expKey,Map<String, String> paramMap) throws EvaluationException{
		Evaluator evaluator = new Evaluator();
		String exp=getConfValue(expKey);
		for(Object o : paramMap.keySet()){ 
		    exp=exp.replace(o.toString(), paramMap.get(o.toString()));
		} 
		return evaluator.evaluate(exp);
	}
	
	public static void main(String[] args) {
		try {
			Map<String,String> evaInfoMap=new HashMap<String, String>();
			evaInfoMap.put("num1","3");
			evaInfoMap.put("num2","7");
			System.out.println(doEvaluate("exp1",evaInfoMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

